/**
 * 
 */
package org.neogenesis.web.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import java.util.List;

import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import javax.inject.Named;

import org.neogenesis.web.Configurations;
import org.neogenesis.web.dao.OrganismDAO;
import org.neogenesis.web.dao.PlatformDAO;
import org.neogenesis.web.dao.TypePlatformDAO;
import org.neogenesis.web.exception.NotAnalizablePlatform;
import org.neogenesis.web.model.Organism;
import org.neogenesis.web.model.Platform;
import org.neogenesis.web.model.TypePlatform;
import org.primefaces.event.FileUploadEvent;

/**
 * @author Nancy
 * 
 */
@Named
@SessionScoped
public class PlatformController implements Serializable {

	private Platform platform = new Platform();
	private String fileName;
	private String filePath;

	private FacesContext context = FacesContext.getCurrentInstance();

	private ResourceBundle bundle = context.getApplication().getResourceBundle(
			context, "bundle");

	@Inject
	private PlatformDAO platformDAO;

	@Inject
	private OrganismDAO organismDAO;

	@Inject
	private TypePlatformDAO typePlatformDAO;

	/**
	 * 
	 */
	public PlatformController() {

	}

	public Platform getPlatform() {
		return platform;
	}

	public void setPlatform(Platform platform) {
		this.platform = platform;
	}

	public List<Organism> getOrganisms() {
		List<Organism> organisms = organismDAO.findAll();
		return organisms;
	}

	public String create() {
		Organism organism = organismDAO.find(platform.getOrganism().getId());
		TypePlatform typePlatform = typePlatformDAO.find(platform
				.getTypePlatform().getId());
		platform.setOrganism(organism);
		platform.setTypePlatform(typePlatform);
		try {
			platformDAO.createFromSoftFile(platform, fileName);
			platform = new Platform();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotAnalizablePlatform e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}

	public List<TypePlatform> getTypes() {

		List<TypePlatform> types = typePlatformDAO.findAll();
		return types;

	}

	public String removePlatform() {
		platformDAO.remove(platform);
		return "backToDeleteList";
	}

	public void handleFileUpload(FileUploadEvent event) {
		FacesMessage msg = new FacesMessage("Succesful", event.getFile()
				.getFileName() + " is uploaded.");
		FacesContext.getCurrentInstance().addMessage(null, msg);
		byte[] content = event.getFile().getContents();
		fileName = event.getFile().getFileName();
		try {
			this.filePath = saveFile(fileName, content);
			
		} catch (FileNotFoundException ex) {
			Logger.getLogger(PlatformController.class.getName()).log(
					Level.SEVERE, null, ex);
		} catch (IOException ex) {
			Logger.getLogger(PlatformController.class.getName()).log(
					Level.SEVERE, null, ex);
		}
	}

	public void validateName(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String name = (String) value;

		if (name == null) {
			FacesMessage msg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					bundle.getString("CreatePlatformRequiredMessage_accessionName"),
					bundle.getString("CreatePlatformInsertValid_accessionName"));
			throw new ValidatorException(msg);
		}

		if (name.length() == 0) {
			FacesMessage msg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					bundle.getString("CreatePlatformRequiredMessage_accessionName"),
					bundle.getString("CreatePlatformInsertValid_accessionName"));
			throw new ValidatorException(msg);
		}
		if (platformDAO.findByName(name) != null) {
			FacesMessage msg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					bundle.getString("CreatePlatformAlreadyExists_accessionName"),
					bundle.getString("CreatePlatformInsertNew_accessionName"));
			throw new ValidatorException(msg);
		}

	}

	public void validateTitle(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		String name = (String) value;

		if (name == null) {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					bundle.getString("CreatePlatformRequiredMessage_title"),
					bundle.getString("CreatePlatformInsertValid_title"));
			throw new ValidatorException(msg);
		}

		if (name.length() == 0) {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					bundle.getString("CreatePlatformRequiredMessage_title"),
					bundle.getString("CreatePlatformInsertValid_title"));
			throw new ValidatorException(msg);
		}

	}

	public void validateManufacturer(FacesContext context,
			UIComponent component, Object value) throws ValidatorException {
		String name = (String) value;

		if (name == null) {
			FacesMessage msg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					bundle.getString("CreatePlatformRequiredMessage_manufacturer"),
					bundle.getString("CreatePlatformInsertValid_manufacturer"));
			throw new ValidatorException(msg);
		}

		if (name.length() == 0) {
			FacesMessage msg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					bundle.getString("CreatePlatformRequiredMessage_manufacturer"),
					bundle.getString("CreatePlatformInsertValid_manufacturer"));
			throw new ValidatorException(msg);
		}

	}

	private String saveFile(String name, byte[] content)
			throws FileNotFoundException, IOException {

		String webAppPath = FacesContext.getCurrentInstance()
				.getExternalContext().getRealPath("/");

		filePath = webAppPath + Configurations.uploadPath + name;
		FileOutputStream fos = new FileOutputStream(filePath);
		fos.write(content);
		fos.flush();
		fos.close();
		return filePath;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public List<Platform> getPlatformList() {
		return platformDAO.findAll();
	}

}
